package com.zhang.limit;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 原子类型限流demo
 */
public class AtomicLimitDemo {
    /**
     * 原子类型自增
     */
    private final AtomicInteger atomicInteger = new AtomicInteger(0);

    /**
     * 当前开始时间
     */
    private long startTime = System.currentTimeMillis();

    // 限流的个数
    private final int maxCount = 10;

    // 指定的时间内
    private final long interval = 60;

    /**
     * 判断是否限制成功 (从1开始)
     *
     * @return 是否限制成功
     */
    public boolean limit() {
        atomicInteger.addAndGet(1);
        if (atomicInteger.get() == 1) {
            startTime = System.currentTimeMillis();
            atomicInteger.addAndGet(1);
            return true;
        }
        // 超过了间隔时间，直接重新开始计数
        if (System.currentTimeMillis() - startTime > interval * 1000) {
            startTime = System.currentTimeMillis();
            atomicInteger.set(1);
            return true;
        }
        // 还在间隔时间内,check有没有超过限流的个数
        return atomicInteger.get() <= maxCount;
    }

    public static void main(String[] args) throws InterruptedException {
        AtomicLimitDemo limitDemo = new AtomicLimitDemo();
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 10; i++) {
            executorService.execute(() -> {
                System.out.println(System.currentTimeMillis() + " " + limitDemo.limit());
            });
            TimeUnit.SECONDS.sleep(10);
        }
        executorService.shutdown();
    }
}
